package main

import (
	"golua/km"

	lua "github.com/yuin/gopher-lua"
)

var appExports = map[string]lua.LGFunction{
	"walk":   KMWalkDir,
	"md5":    KMMd5,
	"gzip":   KMGZipCompressFile,
	"gunzip": KMGZipDecompressFile,
}

func LuaModuleKMLoader(L *lua.LState) int {

	modApp := L.SetFuncs(L.NewTable(), appExports)
	L.SetField(modApp, "name", lua.LString("km"))
	L.Push(modApp)

	return 1
}

func KMMd5(L *lua.LState) int {
	path := L.ToString(1) // 读取参数
	md5, err := km.CalculateFileMD5(path)
	if err != nil {
		L.Push(lua.LNil)
		L.Push(lua.LString(err.Error()))
		return 2
	}
	L.Push(lua.LString(md5))
	return 1
}

func KMWalkDir(L *lua.LState) int {
	path := L.ToString(1) // 读取参数
	files, err := km.WalkDir(path)
	if err != nil {
		L.Push(lua.LNil)
		L.Push(lua.LString(err.Error()))
		return 2
	}
	table := L.NewTable()
	for _, file := range files {
		lFile := L.NewTable()
		lFile.RawSetString("name", lua.LString(file.Name))
		lFile.RawSetString("path", lua.LString(file.Path))
		lFile.RawSetString("size", lua.LNumber(file.Size))
		lFile.RawSetString("isDir", lua.LBool(file.IsDir))
		table.Append(lFile)
	}
	L.Push(table)
	return 1
}

func KMGZipCompressFile(L *lua.LState) int {
	srcPath := L.ToString(1) // 读取参数
	dstPath := L.ToString(2)
	err := km.GZipCompressFile(srcPath, dstPath)
	if err != nil {
		L.Push(lua.LString(err.Error()))
		return 1
	}
	return 0
}

func KMGZipDecompressFile(L *lua.LState) int {
	srcPath := L.ToString(1) // 读取参数
	dstPath := L.ToString(2)
	err := km.GZipDecompressFile(srcPath, dstPath)
	if err != nil {
		L.Push(lua.LString(err.Error()))
		return 1
	}
	return 0
}
